﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using MS.InformationManagement.Support;
using MS.InformationManagement.Presenter.SearchSender;
using System.Collections.Generic;
using Microsoft.SharePoint.Linq;
using MS.InformationManagement.DAL.DocumentCenter;
using System.Linq;
using MS.InformationManagement.Presenter.Support;
using System.Web;
using MS.InformationManagement.DAL.DTOs;
using Microsoft.SharePoint;
using System.Text;
using MS.InformationManagement.Support.Constants;

namespace MS.InformationManagement.Controls._CONTROLTEMPLATES.InformationManagerControls
{
    public partial class SearchSender : BaseControl, ISearchSenderView
    {
        #region fields

        private SearchSenderPresenter _presenter;

        #endregion

        #region Properties

        public IEnumerable<Personas> Personas { get; set; }
        public IEnumerable<Entidades> Entidades { get; set; }
        public string NIT_Cedula
        {
            get { return txtNitCedula.Text; }
        }        
        public string Nombres
        {
            get { return txtNombre.Text; }
        }        
        public string Apellidos
        {
            get { return txtApellido.Text; }
        }
        public string Tipo
        {
            get { return ddlTipo.SelectedItem.Text; }
        }
        public List<Remitentes> ListaRemitentes { get; set; }
        public string Source { get { return Page.Request.QueryString["source"]; } }
        public bool ShowTabRadicado
        {
            set
            {
                tabRadicado.Visible = value;
                SearchRadicados.Visible = value;
            }
        }
        public bool AllowMultiplesQueries { get; set; }
        public List<ContactsDTO> ContactosList
        {
            get
            {
                if (Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "ContactosList"] == null)
                    Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "ContactosList"] = new List<ContactsDTO>();
                return Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "ContactosList"] as List<ContactsDTO>;
            }
            set
            {
                Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "ContactosList"] = value;
            }
        }

        public int PageIndex
        {
            get
            {
                return pgrTemplates.PageIndex;
            }
            set
            {
                pgrTemplates.PageIndex = value;
            }
        }

        public int PageSize
        {
            get
            {
                return pgrTemplates.PageSize;
            }
            set
            {
                pgrTemplates.PageSize = value;
            }
        }

        public int TotalRecords
        {
            get
            {
                return pgrTemplates.TotalRecords;
            }
            set
            {
                pgrTemplates.TotalRecords = value;
            }
        }

        public List<Roles> AllowedRibbonActions { get; set; }

        #endregion

        #region Form Events

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.Page.RegisterAjaxLoaderPlugin();
            btnSearch.AddLoader();
            
            pgrTemplates.OnPageChanged += new Pager.PageChangeHandler(pgrTemplates_OnPageChanged);
            pgrTemplates.NumberOfPagesToDisplay = 5;
            pgrTemplates.PreviousLinkText = "<<";
            pgrTemplates.NextLinkText = ">>";
            PageIndex = 0;
            PageSize = 5;

            if (IsPostBack) return;
            
            //SetControls();
            txtNitCedula.RegularExpression(RegularExpresions.EXP_ALFANUMERIC_NO_TILDE, ExceptionConstants.ERROR_INVALID_CHARACTERS, AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
           
            txtApellido.Attributes.Add("onKeyPress","doClick('" + btnSearch.ClientID + "',event)");
            txtNitCedula.Attributes.Add("onKeyPress","doClick('" + btnSearch.ClientID + "',event)");
            txtNombre.Attributes.Add("onKeyPress","doClick('" + btnSearch.ClientID + "',event)");
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                _presenter = new SearchSenderPresenter(this);
                if (IsPostBack) return;
                else
                _presenter.HandleLoad();
                if (!string.IsNullOrEmpty(Request.QueryString.Get("IsOutbound"))) { ctrlHeader.InnerText = "Buscar"; lblBusqueda.Text = "Destinatarios"; }
                else { ctrlHeader.InnerText = "Buscar"; lblBusqueda.Text = "Remitente"; }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void gvSenders_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                gvSenders.PageIndex = e.NewPageIndex;
                _presenter.LoadSenders();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            PageIndex = 0;
            SearchByCriteria();
            pgrTemplates.BuildPager();
            divGridResults.Visible = true;
        }

        private void SearchByCriteria()
        {
            try
            {
                TipoRemitente tipoRemitente = (TipoRemitente)Enum.Parse(typeof(TipoRemitente), ddlTipo.SelectedValue);
                divApellido.Visible = (tipoRemitente == TipoRemitente.Ciudadano);
                //SetControls();
                _presenter.LoadSenders();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void CheckBox_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (!AllowMultiplesQueries)
                {
                    CheckBox chkBx = (CheckBox)sender;
                    GridViewRow row = chkBx.NamingContainer as GridViewRow;
                    Cache["remitenteID"] = row.Cells[1].Text;
                    string response = string.Format("<script type='text/javascript'>window.frameElement.commitPopup(\"{0}\");</script>", row.Cells[1].Text);
                    Context.Response.Write(response);
                    Context.Response.Flush();
                    Context.Response.End();
                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void gvSenders_RowCreated(object sender, GridViewRowEventArgs e)
        {
            try
            {
                var persona = e.Row.DataItem as Personas;
                var entidad = e.Row.DataItem as Entidades;
            
                //Headers
                if (e.Row.RowType == DataControlRowType.Header)
                {
                    e.Row.Cells[4].Visible = false;
                    e.Row.Cells[5].Visible = false;
                    e.Row.Cells[6].Visible = false;

                    Label lblTitulo2 = e.Row.FindControl("lblTitulo2") as Label;
                    Label lblTitulo3 = e.Row.FindControl("lblTitulo3") as Label;
                    lblTitulo2.Text = ddlTipo.SelectedValue == "Ciudadano" ? "Nombre" : "Razón Social";
                    lblTitulo3.Text = ddlTipo.SelectedValue == "Ciudadano" ? "Teléfono" : "Representante";
                }

                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    e.Row.Cells[4].Visible = false;
                    e.Row.Cells[5].Visible = false;
                    e.Row.Cells[6].Visible = false;

                    Label lblContent2 = e.Row.FindControl("lblContent2") as Label;
                    Label lblContent3 = e.Row.FindControl("lblContent3") as Label;
                    lblContent2.Text = ddlTipo.SelectedValue == "Ciudadano" ? persona.NombreCompleto : entidad.RazónSocial ;
                    lblContent3.Text = ddlTipo.SelectedValue == "Ciudadano" ? persona.Teléfono : entidad.Representante;                
                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void ddlTipo_SelectedIndexChanged(object sender, EventArgs e)
        {
            TipoRemitente tipoRemitente = (TipoRemitente)Enum.Parse(typeof(TipoRemitente), ddlTipo.SelectedValue);
            divApellido.Visible = (tipoRemitente == TipoRemitente.Ciudadano);
            
            ClearGrid();
            pgrTemplates.BuildPager();
            divGridResults.Visible = false;
        }

        protected void btnClose_Click(object sender, EventArgs e)
        {
            this.CloseWindow();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in gvSenders.Rows)
            {
                Label lblTitulo3 = (Label)gvSenders.HeaderRow.FindControl("lblTitulo3");

                if (row.RowType == DataControlRowType.DataRow)
                {
                    CheckBox chkBx = (CheckBox)row.FindControl("chkSelect");
                    if (chkBx != null)
                    {
                        if (chkBx.Checked == true)
                        {
                            Label lblContent2 = (Label)row.FindControl("lblContent2");
                            Label lblContent3 = (Label)row.FindControl("lblContent3");


                            string representante = lblTitulo3.Text == "Teléfono" ? null : lblContent3.Text;
                            ContactosList.RemoveAll(x => x.Id == row.Cells[1].Text);
                            ContactosList.Add(new ContactsDTO { Id = row.Cells[1].Text, Nombre = lblContent2.Text, Direccion = row.Cells[4].Text, Representante = representante, Telefono = row.Cells[5].Text, Email = row.Cells[6].Text });

                            chkBx.Checked = false;
                        }
                    }
                }
            }
            Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "ContactosList"] = ContactosList;
            ConCoipaSelectorID.BindDataGridResult();
        }

        void pgrTemplates_OnPageChanged(object sender, Controls.PageChangeEventArgs e)
        {
            SearchByCriteria();
            pgrTemplates.BuildPager();
        }

        #endregion

        #region Implemented Methods

        public void Show()
        {
            ddlTipo.DataSource = Enum.GetNames(typeof(TipoRemitente)).Where((val, idx) => idx != 1 && idx != 0).ToArray();
            ddlTipo.DataBind();
            var allowedaction = (from act in AllowedRibbonActions
                                 where act.Role.ToUpper() == GlobalConstants.ROLE_CONTACTS.ToUpper()
                                 select act).FirstOrDefault();
            if (allowedaction != null)
                btnContacto.Visible = true;
            else
                btnContacto.Visible = false;
        }

        public void ShowSenders()
        {
            if (ddlTipo.SelectedValue == "Ciudadano")
                gvSenders.DataSource = Personas.ToList();
            else
                gvSenders.DataSource =Entidades.ToList();
            gvSenders.DataBind();
            
            if (gvSenders.Rows.Count > 0)
                pnlMultiResults.Visible = AllowMultiplesQueries;
        }

        #endregion

        #region Private Methods

        private void ClearGrid()
        {
            gvSenders.DataSource = null;
            gvSenders.DataBind();
        }

        //private void SetControls()
        //{
        //    divApellido.Visible = !AllowMultiplesQueries;
        //    divNombre.Visible = !AllowMultiplesQueries;
        //}

        #endregion

     
        protected void btnContacto_Click(object sender, EventArgs e)
        {
            this.DesplegarVentanaModal(SPContext.Current.Web.Url + "/_layouts/MS.InformationManagement.WP/ContactsManager.aspx?Dlg=1", "Sistema de Gestión Documental", 500, 460, this.Page);
        }
        
       

    }
}
